<template>
  <div class="classify-contian">
    <van-sticky>
      <van-search
        v-model="value"
        placeholder="请输入搜索关键词"
        @focus="$router.push('/search')"
      />
    </van-sticky>

    <div class="box">
      <div class="left">
        <van-sidebar v-model="activeKey">
          <van-sidebar-item
            v-for="item in classifyList"
            :key="item.id"
            :title="item.title"
            @click="clickhandler($event, item.id)"
          />
        </van-sidebar>
      </div>

      <div class="list">
        <img v-if="classify.img_url" :src="classify.img_url" />
        <van-empty
          v-if="goodsList.length === 0"
          class="custom-image"
          image="https://img01.yzcdn.cn/vant/custom-empty-image.png"
          description="暂无商品"
        />
        <van-card
          v-for="item in goodsList"
          :key="item.id"
          num="2"
          :price="item.sell_price + '.00'"
          :origin-price="item.market_price"
          :title="item.title"
          :thumb="item.thumb_path"
          @click="$router.push(`/particulars/${item.id}`)"
        />
      </div>
    </div>
  </div>
</template>

<script setup>
import { reqgetCategory, reqgetCategoryGoods } from "@/api";
import { ref, onMounted } from "vue";
const value = ref("");
const activeKey = ref(0);
const classifyList = ref([]);
const classify = ref({});
const goodsList = ref([]);

const clickhandler = (e, id) => {
  // 防止多次点击同一个分类，发多次请求
  if (classify.value.id === id) {
    return;
  }
  // classify.value = classifyList.value[index];
  classify.value = classifyList.value.find((item) => item.id === id);
  getCategoryGoods();
};

// 获取所有分类
const getCategory = async () => {
  let data = await reqgetCategory();
  classifyList.value = data;
  classify.value = data[0];
};

// 获取分类的商品
const getCategoryGoods = async () => {
  let data = await reqgetCategoryGoods(classify.value.id);
  goodsList.value = data;
};

onMounted(async () => {
  await getCategory();
  getCategoryGoods();
});
</script>

<style lang="scss" scoped>
.classify-contian {
  .box {
    display: flex;
    justify-content: space-between;
    background: #fff;

    .left {
      width: 80px;
      height: 100vh;
    }

    .list {
      display: flex;
      flex: 1;
      flex-direction: column;
      height: 100vh;
      overflow: auto;

      img {
        width: 255px;
        height: 76px;
        margin: 0 auto;
      }

      .van-card__price {
        color: orange;
      }
    }
  }
}
</style>